package io.github.shang11925.sbvuewelearn.service.impl;

import io.github.shang11925.sbvuewelearn.dao.CoursesRepository;
import io.github.shang11925.sbvuewelearn.dto.CoursesDTO;
import io.github.shang11925.sbvuewelearn.entity.Courses;
import io.github.shang11925.sbvuewelearn.service.CoursesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CoursesServiceImpl implements CoursesService {
    @Autowired
    CoursesRepository coursesRepository;

    @Override
    public List<Courses> findAll() {
        return coursesRepository.findAll();
    }

    @Override
    public void add(CoursesDTO coursesDTO) {
        Courses courses = new Courses();
        courses.setTitle(coursesDTO.getTitle());
        courses.setDescription(coursesDTO.getDescription());

        courses.setCreatedAt(LocalDateTime.now());

        coursesRepository.save(courses);
    }

    @Override
    @Transactional
    public void update(Long courseId, CoursesDTO coursesDTO) {
        Courses course = coursesRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("课程不存在"));

        course.setTitle(coursesDTO.getTitle());
        course.setDescription(coursesDTO.getDescription());
        coursesRepository.save(course);
    }
}
